package id.co.shuba.spamobile.activities;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;

import id.co.shuba.spamobile.App;
import id.co.shuba.spamobile.Configs;
import id.co.shuba.spamobile.CustomSessionApplication;
import id.co.shuba.spamobile.IDatePickerDialog;
import id.co.shuba.spamobile.IDatePickerTarget;
import id.co.shuba.spamobile.LogoutReceiver;
import id.co.shuba.spamobile.R;
import id.co.shuba.spamobile.Sessions;
import id.co.shuba.spamobile.data.AreaDB;
import id.co.shuba.spamobile.data.AuditDB;
import id.co.shuba.spamobile.data.DSARDB;
import id.co.shuba.spamobile.data.DatabaseHandler;
import id.co.shuba.spamobile.data.FlagFreezeDB;
import id.co.shuba.spamobile.data.HolidayDB;
import id.co.shuba.spamobile.data.StandardDB;
import id.co.shuba.spamobile.data.ProspectDB;
import id.co.shuba.spamobile.data.ProspectProgressDB;
import id.co.shuba.spamobile.data.TransactionLogDB;
import id.co.shuba.spamobile.dialog.DatePickerFragment;
import id.co.shuba.spamobile.model.DSARInfo;
import id.co.shuba.spamobile.model.ErrorInfo;
import id.co.shuba.spamobile.model.FlagFreezeInfo;
import id.co.shuba.spamobile.model.MaintenanceVisitInfo;
import id.co.shuba.spamobile.model.ProspectInfo;
import id.co.shuba.spamobile.model.ProspectProgressInfo;
import id.co.shuba.spamobile.model.StandardInfo;
import id.co.shuba.spamobile.model.UserInfo;
import id.co.shuba.spamobile.services.WebServiceHelper;
import id.co.shuba.spamobile.task.AsyncTaskResult;
import id.co.shuba.spamobile.task.LoginTask;
import id.co.shuba.spamobile.util.AuditUtil;
import id.co.shuba.spamobile.util.Base64;
import id.co.shuba.spamobile.util.DialogUtil;
import id.co.shuba.spamobile.util.SpinnerUtil;
import id.co.shuba.spamobile.util.Str;
import id.co.shuba.spamobile.util.ValidationUtil;
import id.co.shuba.spamobile.widget.CustomArrayAdapter;
import id.co.shuba.spamobile.widget.StandardAdapter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.AsyncTask.Status;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.IntentFilter;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.support.v4.app._ActionBarSherlockTrojanHorse;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.format.DateFormat;
import android.text.method.DateTimeKeyListener;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class FormPipelineActivity extends SherlockFragmentActivity implements
		OnItemSelectedListener, IDatePickerDialog, IDatePickerTarget {
	
	private static final int DATE_DIALOG_ID = 212;	
	private static final int TIME_DIALOG_ID = 213;
	
	private Spinner spnKodya;
	private Spinner spnKecamatan;
	private Spinner spnKelurahan;
	private EditText txtFullName;
	private EditText txtPlafonPlan;
	private EditText txtMobilePhone;
	private EditText txtOfficePhone;
	private EditText txtResidentialPhone;
	private EditText txtReference;	
	private EditText txtAddress;
	private Spinner spnJenisPekerjaan;
	private Spinner spnChanneling;
	private Spinner spnDebtType;
	private Spinner spnExternalType;
	//private EditText txtPostalCode;
	private Spinner spnProspectType;
	private EditText txtVisitPlan;
	private EditText txtPrn;
	private LinearLayout pnlPrn;
	private EditText txtVisitPlanTime;
	private ImageButton btnPick;
	private ImageButton btnPickVisitPlanTime;
	private Spinner spnPostalCode;
	//private Button btnPick;
		
	private DatabaseHandler _db;
	private ProspectDB _pipelineDB;
	private StandardDB _optionDB;
	private AreaDB _areaDB;
	private DSARDB _dsarDB;
	private FlagFreezeDB _flagFreezeDB;
	private String _prospectID;
	private ProspectInfo _info;	
	private String _kecamatan;
	private String _kelurahan;
	private String _postalCode;
	private String _externalType;
	
	private String _defaultOption;
	private UserInfo _user;
	
	private SaveTask _task;
	
	private LogoutReceiver logoutReceiver;

	private void setUpLogoutReceiver() {
		IntentFilter intentFilter = new IntentFilter();
	    intentFilter.addAction("id.co.shuba.spamobile.ACTION_LOGOUT");
	    logoutReceiver = new LogoutReceiver(this);
	    registerReceiver(logoutReceiver, intentFilter);
	}
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {

		menu.add("Save")
		.setIcon(id.co.shuba.spamobile.R.drawable.ic_action_save)
        .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);

        return true;             
    }
	
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getTitle() == "Save") {
			save();
		}
		
	    return super.onOptionsItemSelected(item);
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_form_pipeline);
		setUpLogoutReceiver();
		
		_user = Sessions.getUser(this);
		_defaultOption = getString(R.string.default_option);
		_prospectID = null;
		
		setControls();

		_db = new DatabaseHandler(this);
		_pipelineDB = new ProspectDB(_db);
		_optionDB = new StandardDB(_db);
		_areaDB = new AreaDB(_db);
		_dsarDB = new DSARDB(_db);
		_flagFreezeDB = new FlagFreezeDB(_db);

		initListener();

		fillSpinner();		
		
		Intent intent = getIntent();
		if (intent.hasExtra("prospectID")) {
			setTitle("Ubah Pipeline");
			_prospectID = intent.getStringExtra("prospectID");
			_info = _pipelineDB.get(_prospectID);
			
			_kecamatan = _info.getKecamatanBusiness();
			_kelurahan = _info.getKelurahanBusiness();
			_postalCode = _info.getZipCodeBusiness();
			_externalType = _info.getEksternal();
			
			if (_info.isComplete()) {
				Toast.makeText(this, "Prospect sudah closed", Toast.LENGTH_SHORT).show();				
				finish();
			}			
			
			DSARInfo dsar = _dsarDB.get(_prospectID);
			loadData(_info, dsar);	
			fillDateVisit();
			
			setFlagFreezeState(_info.getFlagFreeze());
			checkHasProspectNo();			
			//setMode(!Str.isNullOrEmpty(_info.getProspectNo()));
						
		} else {
			setTitle("Buat Pipeline");
			txtVisitPlan.setText(DateFormat.format(
					"dd-MM-yyyy", App.processDate.getTime()));
			txtVisitPlanTime.setText("00:00");
		}
		
		Object obj = getLastCustomNonConfigurationInstance();
		if (obj != null) {		
			Object[] states = (Object[])obj;
			_task = (SaveTask) states[0];
			String[] area = (String[]) states[1];
			_kecamatan = area[0];
			_kelurahan = area[1];
			_postalCode = area[2];
			_externalType = area[3];
			
			if (_task != null) {
				ProgressDialog dialog = new ProgressDialog(this);
				dialog.setMessage("Saving...");
				dialog.setCancelable(false);
				_task.setDialog(dialog);
			}
		}
	}		
	
	@Override protected void onStart() {
		super.onStart();
	}
	
	private void initListener() {
		spnKodya.setOnItemSelectedListener(this);
		spnKecamatan.setOnItemSelectedListener(this);
		spnKelurahan.setOnItemSelectedListener(this);		
		spnChanneling.setOnItemSelectedListener(this);	
	}
	
	private void fillDateVisit() {
		DSARDB dsarDB = new DSARDB(_db);
		DSARInfo info = dsarDB.get(_prospectID);
		if (info != null) {
			txtVisitPlan.setText(DialogUtil.changeFormat(info.getDateVisitPlan()));
		} else {
			Log.i("FormPipelineActivity.fillDateVisit", "DSAR Info not found");
		}
	}	
	
	private void checkHasProspectNo() {
		if (_info.getProspectNo() != null && !"n/a".equalsIgnoreCase(_info.getProspectNo().trim())) {
			spnProspectType.setEnabled(false);
			spnChanneling.setEnabled(false);
			spnDebtType.setEnabled(false);
		}			
	}
	
	private void setMode(boolean editable) {
		/*
		txtFullName.setFocusable(editable);
		txtPlafonPlan.setFocusable(editable);
		txtMobilePhone.setFocusable(editable);
		txtOfficePhone.setFocusable(editable);
		txtResidentialPhone.setFocusable(editable);
		txtReference.setFocusable(editable);		
		txtAddress.setFocusable(editable);

		spnKodya.setEnabled(editable);
		spnKecamatan.setFocusable(editable);
		spnKelurahan.setFocusable(editable);
		*/
 		
		spnJenisPekerjaan.setFocusable(editable);
		spnChanneling.setFocusable(editable);
		spnDebtType.setFocusable(editable);
		
		
		/*
		spnExternalType.setFocusable(editable);		
		spnProspectType.setFocusable(editable);

		txtVisitPlan.setFocusable(editable);
		txtVisitPlanTime.setFocusable(editable);	
		
		btnPick.setVisibility(editable? View.VISIBLE : View.GONE);
		btnPickVisitPlanTime.setVisibility(editable? View.VISIBLE : View.GONE);
		*/
	}
	
	private void fillSpinner() {
		fillKodya();

		SpinnerUtil.fillStandard(this, _optionDB, spnJenisPekerjaan, StandardDB.GROUP_JOB, _defaultOption);
		SpinnerUtil.fillStandard(this, _optionDB, spnChanneling, StandardDB.GROUP_CHANNELING2, _defaultOption);
		SpinnerUtil.fillStandard(this, _optionDB, spnDebtType, StandardDB.GROUP_DEBTOR_TYPE, _defaultOption);
		SpinnerUtil.fillStandard(this, _optionDB, spnExternalType, StandardDB.GROUP_EXTERNAL_TYPE, _defaultOption);		
		SpinnerUtil.fillStandard(this, _optionDB, spnProspectType, StandardDB.GROUP_PROSPECT_TYPE, _defaultOption);
		fillExternal();
	}
	
	private void fillExternal() {
		String channelID = SpinnerUtil.optionGetSelectedValue(spnChanneling, _defaultOption);		
		List<StandardInfo> list = Str.isNullOrEmpty(channelID)? new ArrayList<StandardInfo>() : _optionDB.getExternalMappingList(channelID);
		list.add(0, new StandardInfo(_defaultOption, _defaultOption));
		StandardAdapter adapter = new StandardAdapter(this, list);
		spnExternalType.setAdapter(adapter);
		
		SpinnerUtil.optionSetSelectedValue(spnExternalType, _externalType);
	}

	private void setControls() {
		txtFullName = (EditText) findViewById(R.id.txtFullName);
		txtPlafonPlan = (EditText) findViewById(R.id.txtPlafonPlan);
		txtMobilePhone = (EditText) findViewById(R.id.txtMobilePhone);
		txtOfficePhone = (EditText) findViewById(R.id.txtOfficePhone);
		txtResidentialPhone = (EditText) findViewById(R.id.txtHomePhone);
		txtReference = (EditText) findViewById(R.id.txtReference);		
		txtAddress = (EditText) findViewById(R.id.txtWorkAddress);

		spnKodya = (Spinner) findViewById(R.id.spnDistrict);
		spnKecamatan = (Spinner) findViewById(R.id.spnSubDistrict);
		spnKelurahan = (Spinner) findViewById(R.id.spnVillage);

		spnJenisPekerjaan = (Spinner) findViewById(R.id.spnJobType);
		spnChanneling = (Spinner) findViewById(R.id.spnChanneling);
		spnDebtType = (Spinner) findViewById(R.id.spnDebtType);
		spnExternalType = (Spinner) findViewById(R.id.spnOutsiders);
		//txtPostalCode = (EditText) findViewById(R.id.txtPostalCode);
		spnProspectType = (Spinner) findViewById(R.id.spnProspectType);

		txtVisitPlan = (EditText) findViewById(R.id.txtVisitPlan);
		txtVisitPlanTime = (EditText) findViewById(R.id.txtVisitPlanTime);
		spnPostalCode = (Spinner) findViewById(R.id.spnPostalCode);
		//txtPostalCode.setFocusable(false);
		
		txtPrn = (EditText) findViewById(R.id.txtPrn);
		txtPrn.setFocusable(false);
		
		pnlPrn = (LinearLayout) findViewById(R.id.pnlPrn);
		
		btnPick = (ImageButton) findViewById(R.id.btnPick);
		btnPickVisitPlanTime = (ImageButton) findViewById(R.id.btnPickVisitPlanTime);
				
		InputFilter filter = new InputFilter() { 	        
			@Override
			public CharSequence filter(CharSequence source, int start, int end,
					Spanned arg3, int arg4, int arg5) {
				for (int i = start; i < end; i++) { 
                    if (!Character.isDigit(source.charAt(i))) { 
                            return ""; 
                    } 
	            }             
				return null;
			} 
		}; 

		InputFilter[] filters = new InputFilter[] { filter };
		txtMobilePhone.setFilters(filters);
		txtOfficePhone.setFilters(filters);
		txtResidentialPhone.setFilters(filters);
		/*
		spnJenisPekerjaan.setFocusable(true);
		spnJenisPekerjaan.setFocusableInTouchMode(true);		
		spnKodya.setFocusable(true);
		spnKodya.setFocusableInTouchMode(true);
		spnKecamatan.setFocusable(true);
		spnKecamatan.setFocusableInTouchMode(true);
		spnKelurahan.setFocusable(true);
		spnKelurahan.setFocusableInTouchMode(true);
		spnProspectType.setFocusable(true);
		spnProspectType.setFocusableInTouchMode(true);		
		spnChanneling.setFocusable(true);
		spnChanneling.setFocusableInTouchMode(true);
		spnExternalType.setFocusable(true);
		spnExternalType.setFocusableInTouchMode(true);
		spnDebtType.setFocusable(true);
		spnDebtType.setFocusableInTouchMode(true);*/			
		
		//btnPick = (Button) findViewById(R.id.btnPick);		
	}

	private void loadData(ProspectInfo info, DSARInfo dsar) {		
		txtFullName.setText(info.getFullName());
		SpinnerUtil.optionSetSelectedValue(spnJenisPekerjaan, info.getJenisUsaha());
		SpinnerUtil.optionSetSelectedValue(spnChanneling, info.getChanneling());
		SpinnerUtil.optionSetSelectedValue(spnDebtType, info.getDebtorType());
		SpinnerUtil.optionSetSelectedValue(spnExternalType, info.getEksternal());
		//txtPostalCode.setText(info.getZipCodeBusiness());
		SpinnerUtil.optionSetSelectedValue(spnProspectType, info.getProspectType());
				
		SpinnerUtil.areaSetSelectedValue(spnKodya, info.getKodyaKabBusiness());		
		SpinnerUtil.areaSetSelectedValue(spnKecamatan, info.getKecamatanBusiness());
		SpinnerUtil.areaSetSelectedValue(spnKelurahan, info.getKelurahanBusiness());		
		SpinnerUtil.areaSetSelectedValue(spnPostalCode, info.getZipCodeBusiness());
		//SpinnerUtil.area
		
		//txtPostalCode.setText(info.getZipCodeBusiness());
		txtAddress.setText(info.getAddressBusiness());
		txtPlafonPlan.setText(String.valueOf(info.getRencanaPlafon()));
		txtMobilePhone.setText(info.getMobilePhone());
		txtOfficePhone.setText(info.getOfficePhone());
		txtResidentialPhone.setText(info.getResidentialPhone());		
		txtReference.setText(info.getReferensi());	
		
		if (dsar != null) {
			txtVisitPlan.setText(DialogUtil.changeFormat(dsar.getDateVisitPlan()));
			txtVisitPlanTime.setText(dsar.getTimeVisitPlan());
								
			if (!Str.isNullOrEmpty(dsar.getObjectiveOfVisit())) {
				txtVisitPlan.setFocusable(false);
				txtVisitPlanTime.setFocusable(false);
				
				btnPick.setVisibility(View.GONE);
				btnPickVisitPlanTime.setVisibility(View.GONE);
			}
		}
				
		if (info.getProspectNo() != null && !"n/a".equalsIgnoreCase(info.getProspectNo().trim()) && !"".equals(info.getProspectNo())) {				
			pnlPrn.setVisibility(View.VISIBLE);
			txtPrn.setText(info.getProspectNo());
		}	
				 
        
	}	
	
	private void setFlagFreezeState(int flag) {
		List<FlagFreezeInfo> fi = _flagFreezeDB.getList(flag);
        for (FlagFreezeInfo item : fi)
        {
        	boolean enabled = "1".equals(item.getEnabled());
        	if ("PROSTYPE".equalsIgnoreCase(item.getField())) {
        		spnProspectType.setEnabled(enabled);
        	} else if ("DEBTYPE".equalsIgnoreCase(item.getField())) {
        		spnDebtType.setEnabled(enabled);
        	} else if ("CHANNEL".equalsIgnoreCase(item.getField())) {
        		spnChanneling.setEnabled(enabled);
        	} else if ("EXTERNAL".equalsIgnoreCase(item.getField())) {
        		spnExternalType.setEnabled(enabled);
        	} else if ("REFERENSI".equalsIgnoreCase(item.getField())) {
        		txtReference.setFocusable(enabled);
        	}     	        	        
        }
	}
	
	private ProspectInfo getData() {
		UserInfo user = Sessions.getUser(this);
		return getData(user);
	}
	
	private ProspectInfo getData(UserInfo user) {
		ProspectInfo info = new ProspectInfo();
		info.setProspectNo(txtPrn.getText().toString());
		info.setFullName(txtFullName.getText().toString());
		info.setAddressBusiness(txtAddress.getText().toString());		
		info.setMobilePhone(txtMobilePhone.getText().toString());
		info.setOfficePhone(txtOfficePhone.getText().toString());
		info.setResidentialPhone(txtResidentialPhone.getText().toString());
		info.setReferensi(txtReference.getText().toString());			
		info.setKodyaKabBusiness(SpinnerUtil.areaGetSelectedValue(spnKodya, _defaultOption));
		info.setKecamatanBusiness(SpinnerUtil.areaGetSelectedValue(spnKecamatan, _defaultOption));
		info.setKelurahanBusiness(SpinnerUtil.areaGetSelectedValue(spnKelurahan, _defaultOption));
		info.setJenisUsaha(SpinnerUtil.optionGetSelectedValue(spnJenisPekerjaan, _defaultOption));
		info.setProspectType(SpinnerUtil.optionGetSelectedValue(spnProspectType, _defaultOption));
		info.setEksternal(SpinnerUtil.optionGetSelectedValue(spnExternalType, _defaultOption));
		info.setChanneling(SpinnerUtil.optionGetSelectedValue(spnChanneling, _defaultOption));
		info.setZipCodeBusiness(SpinnerUtil.areaGetSelectedValue(spnPostalCode, _defaultOption));
		info.setDebtorType(SpinnerUtil.optionGetSelectedValue(spnDebtType, _defaultOption));
		info.setVisitDate(DialogUtil.changeFormat(txtVisitPlan.getText().toString()));
		info.setTimeVisitPlan(txtVisitPlanTime.getText().toString());
		
		try {
			info.setRencanaPlafon(Long.parseLong(txtPlafonPlan.getText().toString()));
		} catch (Exception e) {
			info.setRencanaPlafon(0);
		}		
		
		String date = App.getProcessDateTime();
		
		if (_info == null) {
			info.setEntryBy(user.getNip());
			info.setEntryDate(date);	
			info.setPipelineStartTime(date);
		} else {
			info.setEntryBy(_info.getEntryBy());
			info.setEntryDate(_info.getEntryDate());
		}	
		
		info.setUpdateBy(user.getNip());
		info.setUpdateDate(date);
		
		info.setIsUpload("0");
		
		return info;
	}	
	
	private List<ErrorInfo> validate(ProspectInfo info) {		
		List<ErrorInfo> errors = new ArrayList<ErrorInfo>();		
		if (info.getFullName().length() < 3)
			errors.add(new ErrorInfo(txtFullName, getString(R.string.full_name), "Nama lengkap harus diisi. Minimal 3 karakter"));
		if (info.getFullName().length() > 50)
			errors.add(new ErrorInfo(txtFullName, getString(R.string.full_name), "Nama lengkap maksimal 50 karakter"));
		if (info.getJenisUsaha() == null)
			errors.add(new ErrorInfo(spnJenisPekerjaan, getString(R.string.job_type)));		
		if (info.getRencanaPlafon() < 1)
			errors.add(new ErrorInfo(txtPlafonPlan, getString(R.string.plafon_plan)));
							
		boolean validPhone = info.getMobilePhone().length() > 5
				|| info.getResidentialPhone().length() > 5
				|| info.getOfficePhone().length() > 5;		
		if (!validPhone)
			errors.add(new ErrorInfo(txtMobilePhone, "Phone Number", "Wajib mengisi salah satu nomor telepon"));
		
		
		if (info.getMobilePhone().length() > 18)
			errors.add(new ErrorInfo(txtMobilePhone, getString(R.string.mobile_phone), "Maksimal telepon seluler 18 karakter"));
		if (info.getOfficePhone().length() > 12)
			errors.add(new ErrorInfo(txtOfficePhone, getString(R.string.office_phone), "Maksimal telepon kantor 12 karakter"));
		if (info.getResidentialPhone().length() > 12)
			errors.add(new ErrorInfo(txtResidentialPhone, getString(R.string.home_phone, "Maksimal telepon rumah 12 karakter"))); 		
		
		if (info.getKodyaKabBusiness() == null)
			errors.add(new ErrorInfo(spnKodya, getString(R.string.district)));
		if (info.getKecamatanBusiness() == null)
			errors.add(new ErrorInfo(spnKecamatan, getString(R.string.sub_district)));
		if (info.getKelurahanBusiness() == null)
			errors.add(new ErrorInfo(spnKelurahan, getString(R.string.village)));
		if (info.getZipCodeBusiness() == null)
			errors.add(new ErrorInfo(spnPostalCode, getString(R.string.postal_code)));
		if (_info == null && !DialogUtil.isValidAfterward(info.getVisitDate()))
			errors.add(new ErrorInfo(txtVisitPlan, getString(R.string.visit_date), "Tanggal rencana kunjungan tidak boleh kurang dari tanggal sekarang"));
		if (info.getProspectType() == null)
			errors.add(new ErrorInfo(spnProspectType, getString(R.string.prospect_type)));
		if (info.getDebtorType() == null)
			errors.add(new ErrorInfo(spnDebtType, getString(R.string.debtor)));
		if (info.getChanneling() == null)
			errors.add(new ErrorInfo(spnChanneling, getString(R.string.channelling)));
		if (info.getAddressBusiness().length() < 1)
			errors.add(new ErrorInfo(txtAddress, getString(R.string.work_address)));
		if (info.getAddressBusiness().length() > 255)
			errors.add(new ErrorInfo(txtAddress, getString(R.string.work_address), "Alamat Usaha maksimal 255 karakter"));
		
		int extCount = spnExternalType.getAdapter().getCount(); 
		if (extCount > 1 && info.getEksternal() == null)
			errors.add(new ErrorInfo(spnExternalType, getString(R.string.outsiders)));
		
		return errors;
	}	

	public void onItemSelected(AdapterView<?> adapter, View arg1, int arg2,
			long arg3) {
		String value = null;
		switch (adapter.getId()) {
		case R.id.spnDistrict:
			value = (String)adapter.getSelectedItem();
			fillKecamatan(value);
			
			SpinnerUtil.areaSetSelectedValue(spnKecamatan, _kecamatan);
			break;
		case R.id.spnSubDistrict:			
			fillKelurahan((String)spnKodya.getSelectedItem(),
					(String)spnKecamatan.getSelectedItem());
			
			SpinnerUtil.areaSetSelectedValue(spnKelurahan, _kelurahan);
			break;
		case R.id.spnVillage:			
			fillPostalCode((String)spnKodya.getSelectedItem(),
					(String)spnKecamatan.getSelectedItem(),
					(String)spnKelurahan.getSelectedItem());
			
			SpinnerUtil.areaSetSelectedValue(spnPostalCode, _postalCode);
			break;
		case R.id.spnChanneling:
			fillExternal();
		}
	}
	
	private void fillPostalCode(String kodya, String kecamatan, String kelurahan) {				
		List<String> list = _areaDB.getPostalCodeList(_user.getAoCode(), kodya, kecamatan, kelurahan);		
		list.add(0, _defaultOption);
		CustomArrayAdapter adapter = new CustomArrayAdapter(this, R.layout.area_item, list);
		spnPostalCode.setAdapter(adapter);		
	}

	private void fillKodya() {
		List<String> list = _areaDB.getKodyaList(_user.getAoCode());		
		list.add(0, _defaultOption);
		CustomArrayAdapter adapter = new CustomArrayAdapter(this, R.layout.area_item, list);
		spnKodya.setAdapter(adapter);
		fillKecamatan((String)spnKodya.getSelectedItem());
	}

	private void fillKecamatan(String kodya) {		
		List<String> list = _areaDB.getKecamatanList(_user.getAoCode(), kodya);
		list.add(0, _defaultOption);
		
		CustomArrayAdapter adapter = new CustomArrayAdapter(this, R.layout.area_item, list);
		spnKecamatan.setAdapter(adapter);
		fillKelurahan((String)spnKodya.getSelectedItem(), (String)spnKecamatan.getSelectedItem());
	}

	private void fillKelurahan(String kodya, String kecamatan) {
		List<String> list = _areaDB.getKelurahanList(_user.getAoCode(), kodya, kecamatan);
		list.add(0, _defaultOption);
		CustomArrayAdapter adapter = new CustomArrayAdapter(this, R.layout.area_item, list);
		spnKelurahan.setAdapter(adapter);
		fillPostalCode((String)spnKodya.getSelectedItem(),
				(String)spnKecamatan.getSelectedItem(),
				(String)spnKelurahan.getSelectedItem());
	}

	public void onNothingSelected(AdapterView<?> arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void onDestroy() {
		unregisterReceiver(logoutReceiver);
		if (_db != null)
			_db.close();
		super.onDestroy();			
	}
	
	private void save() {
		try {			
			ProspectInfo info = getData();					
			List<ErrorInfo> errors = validate(info);
						
			if (errors.size() == 0) {
				ProgressDialog dialog = new ProgressDialog(this);
				dialog.setMessage("Saving...");
				dialog.setCancelable(false);
				_task = new SaveTask(info, dialog);
				_task.execute("N");													
			} else {
				ValidationUtil.showValidationDialog(this, errors, this);
			}													
		} catch (Exception e) {
			e.printStackTrace();
		}		
	}	
		
	public void onDateDialogButtonClick(View v) {		
		//showDialog(DATE_DIALOG_ID);
		
		showDateDialog();
	}	
	
	public void onTimeDialogButtonClick(View v) {		
		showDialog(TIME_DIALOG_ID);		
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG_ID:
			return DialogUtil.create(this, txtVisitPlan);
		case TIME_DIALOG_ID:
			return DialogUtil.createTimePicker(this, txtVisitPlanTime);
		}
		
		return null;
	}
	
	private void showDateDialog() {
		/*
		DatePickerFragment fr = new DatePickerFragment();
		fr.setTarget(txtVisitPlan);
		fr.show(getSupportFragmentManager(), "datePicker");*/
		showDialog(DATE_DIALOG_ID);
	}

	public void show(EditText txt) {		
		showDateDialog();
	}

	public EditText getEditText() {		
		return txtVisitPlan;
	}
	
	@Override
	public void onBackPressed() {
		ProspectInfo info = getData();
		boolean isChanged = false;
		try {			
			isChanged = AuditUtil.isFormChanged(ProspectInfo.class, _info, info, _defaultOption);
		} catch (Exception e) {		
			e.printStackTrace();
		}	
		
		if (!isChanged) {
			finish();
			return;
		}
		
		new AlertDialog.Builder(new ContextThemeWrapper(this,
				R.style.Theme_Sherlock_Light_Dialog))
        .setIcon(android.R.drawable.ic_dialog_alert)
        .setTitle(R.string.confirm)
        .setMessage(R.string.save_changes)
        .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            	dialog.dismiss();
                save();    
            }
        })        
        .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {                
                finish();    
            }
        })
        .show();		
	}	
	
	@Override
	public Object onRetainCustomNonConfigurationInstance() {
		String[] area = new String[]
				{		
				(String)spnKecamatan.getSelectedItem(),
				(String)spnKelurahan.getSelectedItem(),
				(String)spnPostalCode.getSelectedItem(),
				SpinnerUtil.optionGetSelectedValue(spnExternalType, _defaultOption)
				};
		return new Object[] { _task, area };
	}
	
	@Override
	public void onUserInteraction() {		
		super.onUserInteraction();
		
		((CustomSessionApplication) getApplication()).touch();		
	}
	
	private class SaveTask extends AsyncTask<String, Integer, AsyncTaskResult<String>>
	implements OnDismissListener {
		private ProspectInfo _prospect;
		private ProgressDialog _dialog;			
		
		public SaveTask(ProspectInfo prospect, ProgressDialog dialog) {
			_prospect = prospect;
			_dialog = dialog;
		}
		
		public void setDialog(ProgressDialog dialog) {			
			_dialog = dialog;
			if (getStatus() == Status.RUNNING)
				_dialog.show();
		}
		
		@Override
		protected void onPreExecute() {		
			super.onPreExecute();
			_dialog.setOnDismissListener(this);
			_dialog.show();
		}
		
		@Override
		protected AsyncTaskResult<String> doInBackground(String... params) {						
			try {			
				if (_prospect.getProspectNo() != null && _prospect.getProspectNo().length() > 3)						
					return new AsyncTaskResult<String>("EDIT");
					
				if (!App.isNetworkAvailable(FormPipelineActivity.this))
					return new AsyncTaskResult<String>((String)null);
				
				String isNegativeChecking = params[0];
				UserInfo user = Sessions.getUser(FormPipelineActivity.this);
				WebServiceHelper ws = new WebServiceHelper(FormPipelineActivity.this);	
				Map<String, Object> properties = new HashMap<String, Object>();
				properties.put("unitCode", user.getUnitCode());
				properties.put("segmentCode", user.getSourceCode());
				properties.put("prospectType", _prospect.getProspectType());
				properties.put("debtorType", _prospect.getDebtorType());
				properties.put("channeling", _prospect.getChanneling());
				properties.put("custName", _prospect.getFullName());
				properties.put("isNegativeChecking", isNegativeChecking);

				//1min timeout
				String result = ws.Call("GeneratePRN", properties, 10000).toString();
				String strJSON = new String(Base64.decode(result, Base64.GZIP));

				JSONObject res = new JSONObject(strJSON);
				String error = res.getString("error");
				if (error.length() > 0 && !error.equals("null"))
					throw new Exception(error);
								
				String prn = res.getString("result");
				return new AsyncTaskResult<String>(prn);
			} catch (Exception e) {
				e.printStackTrace();
				return new AsyncTaskResult<String>(e);
			}			
		}		
		
		@Override
		protected void onPostExecute(AsyncTaskResult<String> result) {			
			super.onPostExecute(result);
						
			_dialog.dismiss();
									
			if (result.getError() != null || result.getResult() == null) {
				Toast.makeText(FormPipelineActivity.this, "Offline Mode",
						Toast.LENGTH_LONG).show();			
				_prospect.setProspectNo("n/a");				
			}
			
			try {							
				if (result.getError() == null && result.getResult()!= null && !"EDIT".equals(result.getResult())) {
					String[] arrPrn = result.getResult().split(",");
					
					checkCombination(arrPrn[0]);
																												
					if ("0".equals(arrPrn[0])) {						
						negativeFileConfirm(arrPrn);
						return;
		            } else {
		            	_prospect.setProspectNo(arrPrn[0]);
		            	saveLocal();
		            	return;
		            }					
				}
				
				saveLocal();
			} catch (Exception e) {
				e.printStackTrace();
				Toast.makeText(FormPipelineActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();				
			}
		}
		
		private void negativeFileConfirm(String[] arrPrn) {
			String message = String.format(
					"Mode online\n\nTerdapat %d nama : '%s' pada database negative file\n"+
					"Apakah Anda akan melanjutkan proses pipeline untuk calon nasabah tersebut?",
					arrPrn[1], _prospect.getFullName());
			
			new AlertDialog.Builder(new ContextThemeWrapper(FormPipelineActivity.this,
					R.style.Theme_Sherlock_Light_Dialog))
	        .setIcon(android.R.drawable.ic_dialog_alert)
	        .setTitle(R.string.confirm)
	        .setMessage(message)
	        .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
	            public void onClick(DialogInterface dialog, int which) {
	            	dialog.dismiss();
	            	ProgressDialog newDialog = new ProgressDialog(FormPipelineActivity.this);
	            	SaveTask newTask = new SaveTask(_prospect, newDialog);
	            	newTask.execute("N");
	            }
	        })       
	        .setNegativeButton(R.string.no, null)   
	        .show();
		}
		
		private void checkCombination(String str) throws Exception {
			if ("~".equals(str)) 
				throw new Exception("Kombinasi Tipe Prospek, Tipe Debitur dan Tipe Channel tidak valid\n\nSilakan ganti dengan kombinasi yang lain");
		}
		
		private void saveLocal() throws Exception {
			UserInfo user = Sessions.getUser(FormPipelineActivity.this);
			
			HolidayDB hDB = new HolidayDB(_db);
			String dateFollowUp = hDB.addDays(App.processDate, Configs.getGuFup(FormPipelineActivity.this));
			_prospect.setGuFup(dateFollowUp);
			_prospect.setAoCode(user.getAoCode());
			_prospect.setUnitCode(user.getUnitCode());
			
														
			String action = "INSERT";
			if (_prospectID == null) {						
				_prospect.setId(App.createProspectID(user));
				_prospect.setSourceCode(user.getSourceCode());				
				_pipelineDB.add(_prospect);
				
				ProspectProgressInfo progress = new ProspectProgressInfo();
				progress.setProspectID(_prospect.getProspectID());
				progress.setProgressStatus("NEW");
				progress.setEntryBy(_prospect.getUpdateBy());
				progress.setEntryDate(_prospect.getUpdateDate());
				progress.setUpdateBy(_prospect.getUpdateBy());
				progress.setUpdateDate(_prospect.getUpdateDate());			
				
				ProspectProgressDB progDB = new ProspectProgressDB(_db);
				progDB.add(progress);							
			} else {
				action = "UPDATE";
				_prospect.setId(_prospectID);
				_pipelineDB.update(_prospect);
			}	
			
			saveDSAR();
			
			TransactionLogDB trans = new TransactionLogDB(_db);
			trans.add(user.getNip(), action, String.format("%s %s", action, AuditUtil.getPrimaryKeyInfo(_prospect)));
			setResult(Activity.RESULT_OK);
			finish();
		}
		
		private void saveDSAR() {			
			DSARInfo dsar = _dsarDB.get(_prospect.getProspectID());						
			
			if (dsar == null) {
				dsar = new DSARInfo();
				dsar.setProspectID(_prospect.getProspectID());
				dsar.setVisitNo(_dsarDB.generateVisitNo(_prospect.getProspectID()) + 1);
				dsar.setJoinFieldWork("0");
				dsar.setEntryBy(_prospect.getUpdateBy());
				dsar.setEntryDate(_prospect.getUpdateDate());
				dsar.setUpdateBy(_prospect.getUpdateBy());
				dsar.setUpdateDate(_prospect.getUpdateDate());
				dsar.setIsUpload("0");
				dsar.setDateVisitPlan(_prospect.getVisitDate());
				dsar.setTimeVisitPlan(_prospect.getTimeVisitPlan());
				_dsarDB.add(dsar);
			} else {								
				dsar.setUpdateBy(_prospect.getUpdateBy());
				dsar.setUpdateDate(_prospect.getUpdateDate());
				dsar.setIsUpload("0");
				dsar.setDateVisitPlan(_prospect.getVisitDate());
				dsar.setTimeVisitPlan(_prospect.getTimeVisitPlan());
				_dsarDB.updateDateVisitPlan(dsar);
			}
		}

		@Override
		public void onDismiss(DialogInterface dialog) {	
			/*
			new AlertDialog.Builder(new ContextThemeWrapper(FormPipelineActivity.this,
					R.style.Theme_Sherlock_Light_Dialog))
	        .setIcon(android.R.drawable.ic_dialog_alert)
	        .setTitle(R.string.confirm)	      
	        .setCancelable(true)
	        .setMessage("Batalkan prosess?")
	        .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
	            public void onClick(DialogInterface dialog, int which) {	            	
	            	cancel(true);			                                     
	            }})      
	        .setNegativeButton(R.string.no, null)
	        .show();*/ 
		}
		
		
	}
}
